<template>
	<view class="content">
		<view class="table-name" @click="show = true">
			<span>选择宠物</span>
			<span>
				<u-icon name="arrow-right" style="margin-left: 20rpx;margin-top: 5rpx;" color="#999999" size="30"></u-icon>
				{{petValue}}
				<u-select v-model="show" :list="DataList" @confirm="confirm"></u-select>
			</span>
		</view>
		<view class="title">
			<input type="text" style="width: 100%;" v-model="title" placeholder="请输入标题"/>
		</view> 
		<view class="taxt" v-if="options.type == 1">
			<textarea v-model="content" placeholder="日记正文…" />
		</view>  
		<view class="table-item" v-if="options.type == 1">
			<view class="table-cloum">
				<span>上传图片</span> 
				<view class="content-upload">
					<view class="uploads" v-for="(item,index) in fileList" :key="index" >
						<!-- <view class="upload-del" @click="del(index)">
							<u-icon name="close" color="#FFFFFF" size="24"></u-icon>
						</view> -->
						<image :src="item" @click="setFileShow(index)" mode=""></image>
						<!-- <image :src="item" @click="getImg(index)" mode=""></image> -->
					</view>
					<view class="uploads-add" @click="upload" v-if="maxCount > fileList.length">
						<u-icon name="plus" color="#606266" size="38"></u-icon>
						<view style="color: #606266;margin-top: 25rpx;">添加图片</view>
					</view>
				</view>
			</view>
		</view>
		<view class="table-item" v-else>
			<view class="table-cloum">
				<span>上传视频</span>
				<view class="addPload-waik">
					<view class="addPload" v-for="(item,index) in srcList" :key="index">
						<view class="addItems">
							<view class="addItems-icon" @click="delVideo(index)"><u-icon name="close" color="#FFFFFF" size="38"></u-icon></view>
							<video :src="item" id="video_play" @play="playVedio"></video>
						</view>
					</view>
					<view class="addItem" @click="test" v-if="srcList.length < 1">
						<u-icon name="plus" color="#f2f2f2" size="80"></u-icon>
					</view>
				</view>
			</view>
		</view>
		<view class="table-location">
			<view :class="!active?'location-item':'location-item2'" @click="active = !active">
				<!-- <u-icon name="map" v-if="active" color="#ffffff" size="48"></u-icon>
				<u-icon name="map" v-else color="#999999" size="48"></u-icon> -->
				<image src="../../../static/img/dingwei2.png" style="width: 32rpx;height: 32rpx;margin: 0 8rpx 0 0;" mode=""></image>
				<view>添加位置</view>
			</view>
		</view>
		<view class="commit" v-if="options.id">
			<view class="commit-nik">
				<view class="save" @click="submitUpdate(1)">
					<image src="../../../static/img/sxbf.png" mode=""></image>
					<span>保存草稿</span>
				</view>
				<u-button class="styleCss" type="warning" @click="submitUpdate(2)">确认修改并发布</u-button>
			</view>
		</view>
		<view class="commit" v-else>
			<view class="commit-nik">
				<view class="save" @click="submit(1)">
					<image src="../../../static/img/sxbf.png" mode=""></image>
					<span>保存草稿</span>
				</view>
				<u-button class="styleCss" type="warning" @click="submit(2)">发表日记</u-button>
			</view>
		</view>
		<u-popup v-model="fileShow" mode="bottom" border-radius="20">
			<view class="fileView">
				<view class="fileView-nik">
					<view class="file-buttom" @click="setfileImg">
						编辑图片
					</view>
					<view class="file-buttom" @click="del">
						<span>删除图片</span>
					</view>
				</view>
			</view>
		</u-popup>
		<!-- <image-croppers :src="tempFilePath" @confirm="confirmCover" @cancel="cancel"></image-croppers> -->
	</view>
</template>

<script>
import VODUpload from '../../../utils/aliyun-upload-sdk-1.0.1.min.js'
import {request} from '../../../utils/request.js'
let srcLists = []
let vId = undefined
let uploader = new VODUpload({
	//网络原因失败时，重新上传次数，默认为3
	retryCount: 3,
	//网络原因失败时，重新上传间隔时间，默认为2秒
	retryDuration: 2,
	//开始上传
	onUploadstarted: function (uploadInfo) {
		console.log('开始上传')
		console.log(uploadInfo)
		// console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
	//获取STS Token，设置到SDK
		uploader.startUpload();
	// uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret, secretToken);
	},
	//文件上传成功
	onUploadSucceed: function (uploadInfo) {
		vId = uploadInfo.videoId
		srcLists.push(uploadInfo.url)
	},
	//文件上传失败
	onUploadFailed: function (uploadInfo, code, message) {
		console.log('文件上传失败')
		console.loglog("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
	},
	//文件上传进度，单位：字节
	onUploadProgress: function (uploadInfo, totalSize, loadedPercent) {
		// console.log('文件上传进度')
		// console.log(uploadInfo)
		// console.loglog("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(loadedPercent * 100) + "%");
	},
	//上传凭证超时
	onUploadTokenExpired: function (uploadInfo) {
		console.log('上传凭证超时')
		resumeUploadWithAuth(uploadInfo)
		console.log("onUploadTokenExpired");
	//重新获取STS token，恢复上传
		uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken);
	},
	//全部文件上传结束
	onUploadEnd:function(uploadInfo){
		console.log('全部文件上传结束')
		console.log(uploadInfo);
	}
})
export default {
	data() {
		return {
			fileShow: false,
			aaaa: undefined,
			// tempFilePath: undefined,
			fileIndex: 0,
			maxCount: 5,
			content: undefined,
			title: undefined,
			show: false,
			videoId: vId,
			active: false,
			srcList: srcLists,
			fileList: [],
			fileList2: [],
			formData: [
				{
					file: '1',
					fileName: ''
				}
			],
			action: this.commonApi.petAvatar,
			userData:{
				images: ''
			},
			longitude: undefined,
			latitude: undefined,
			address: undefined,
			options: {},
			pid: 0,
			petValue: '',
			DataList: [],
			onOf: true,
			fileListNew: []
		}
	},
	onShow() {
		uni.$once('SetTailor',(e)=>{
			let fileName = Number(new Date())
			let self = this
			uni.uploadFile({
				url: self.commonApi.petAvatar,
				filePath: e,
				name: 'file',
				formData: {
					file: '',
					fileName: fileName+'.png'
				},
				success: (res) => {
					let imgList = JSON.parse(res.data)
					self.fileList.splice(self.fileIndex,1,imgList.data)
				}
			})
		})
	},
	methods:{
		// confirmCover(e){   //点击确定裁剪
		// 	console.log(this.fileIndex)
		// 	console.log(e.detail.tempFilePath)
		// 	let fileName = Number(new Date())
		// 	let self = this
		// 	uni.uploadFile({
		// 		url: self.commonApi.petAvatar,
		// 		filePath: e.detail.tempFilePath,
		// 		name: 'file',
		// 		formData: {
		// 			file: '',
		// 			fileName: fileName+'.png'
		// 		},
		// 		success: (res) => {
		// 			let imgList = JSON.parse(res.data)
		// 			self.fileList.splice(self.fileIndex,1,imgList.data)
		// 			// self.fileList[self.fileIndex] = imgList.data
		// 			// self.fileList2[self.fileIndex] = imgList.data
		// 		}
		// 	})
		// 	// this.tempFilePath = ''
		// },
		// cancel(){   //点击取消裁剪
			
		// },
		setfileImg(){
			uni.navigateTo({
				url: '../imgCutVip/mainFirst?url=' + this.fileList[this.fileIndex]
			})
			this.fileShow = false 
		},
		setFileShow(i){
			this.fileShow = true
			this.fileIndex = i
		},
		// getImg(e){
		// 	uni.previewImage({
		// 		urls: [this.fileList[e]]
		// 	});
		// },
		setUploadImg(index){
			let self = this
			let fileName = Number(new Date())
			//如果所有图片都已经上传完，就不再往下执行
			if (index >= self.fileList2.length) {
				index = 0
				self.fileList2 = []
			}else{
				console.log('6666----'+self.fileList2[index])
				self.fileListNew.push(self.fileList2[index])
				uni.uploadFile({
					url: self.commonApi.petAvatar,
					filePath: self.fileList2[index],
					name: 'file',
					formData: {
						file: '',
						fileName: fileName+'.png'
					},
					success: (res) => {
						index++
						let imgList = JSON.parse(res.data)
						self.fileList.push(imgList.data)
						self.setUploadImg(index)
					}
				})
			}
			
		},
		upload() {
			let self = this
			let max = 5 - self.fileList.length
			uni.chooseImage({
				count: max, //默认5
				compressed: false,
				sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有, 'compressed'
				sourceType: ['album'], //从相册选择
				success: (res) => {
					if(self.fileList.length < 5){
						res.tempFiles.forEach(item=>{
							self.fileList2.push(item.path)
						})
						let datas = {
							petValue: self.petValue,
							pid: self.pid,
							title: self.title,
							content: self.content,
							imgFlieList: self.fileList2.toString(),
							imgFlieListOld: self.fileListNew.toString()
						}
						console.log('9999999')
						console.log(self.fileListNew)
						datas = JSON.stringify(datas)
						uni.navigateTo({
							url: '../imgCutVip/main?dataList='+datas
						})
						// self.setUploadImg(0)
					}
				}
			});
		},
		del(){
			this.fileList.splice(this.fileIndex,1)
			this.fileList2.splice(this.fileIndex,1)
			this.fileListNew.splice(this.fileIndex,1)
			this.fileShow = false
		},
		confirm(e){
			this.petValue = e[0].label
			this.pid = e[0].value
		},
		getPet(){
			let uid = uni.getStorageSync('uid')
			this.$request(this.commonApi.petList+uid, 'GET', {}).then(res => {
				if(!this.petValue){
					this.petValue = res.data.data[0].name
				}
				this.pid = res.data.data[0].pid 
				res.data.data.forEach(item=>{
					item = {
						label: item.name,
						value: item.pid
					}
					this.DataList.push(item)
				})
			});
		},
		submitUpdate(e){     //日记草稿修改
			let self = this;
			if(self.options.type == 2){
				if(!self.title){
					uni.showToast({
						title:'标题不能为空',
						duration:500,
						icon:'none'
					})
					return false
				}
				if(self.srcList.length == 0){
					uni.showToast({
						title:'请先上传视频',
						duration:500,
						icon:'none'
					})
					return false
				}
				let data = {
					locationLatitude: self.latitude,
					locationLongitude: self.longitude,
					locationName: self.address,
					petId: self.pid,
					id: self.options.id,
					showFlag: self.active?1:0,
					status: e,
					title: self.title,
					type: 2,
					videoId: vId
				}
				self.$request(self.commonApi.diaryUpdate,'POST',data,'application/json').then(res=>{
					uni.showToast({
						title:'操作成功',
						duration:500,
						icon:'none'
					})
					setTimeout(()=>{
						uni.navigateBack({
							delta: 1
						})
					},500)
				})
			}else{
				if(!self.title){
					uni.showToast({
						title:'标题不能为空',
						duration:500,
						icon:'none'
					})
					return false
				}
				if(self.fileList.length == 0){
					uni.showToast({
						title:'请先上传图片',
						duration:500,
						icon:'none'
					})
					return false
				}
				let data = {
					cover: self.fileList[0],
					locationLatitude: self.latitude,
					locationLongitude: self.longitude,
					locationName: self.address,
					content: self.content,
					id: self.options.id,
					mediaUrl: self.fileList.toString(),
					petId: self.pid,
					showFlag: self.active?1:0,
					status: e,
					title: self.title,
					type: 1,
					videoId: self.videoId
				}
				self.$request(self.commonApi.diaryUpdate,'POST',data,'application/json').then(res=>{
					uni.showToast({
						title:'操作成功',
						duration:500,
						icon:'none'
					})
					setTimeout(()=>{
						uni.navigateBack({
							delta: 1
						})
					},500)
				})
			}
		},
		submit(e){
			let self = this;
			if(self.options.type == 2){
				if(!self.title){
					uni.showToast({
						title:'标题不能为空',
						duration:500,
						icon:'none'
					})
					return false
				}
				if(self.srcList.length == 0){
					uni.showToast({
						title:'请先上传视频',
						duration:500,
						icon:'none'
					})
					return false
				}
				let data = {
					locationLatitude: self.latitude,
					locationLongitude: self.longitude,
					locationName: self.address,
					petId: self.pid,
					showFlag: self.active?1:0,
					status: e,
					title: self.title,
					type: 2,
					videoId: vId
				}
				self.$request(self.commonApi.diaryAdd,'POST',data,'application/json').then(res=>{
					uni.showToast({
						title:'操作成功',
						duration:500,
						icon:'none'
					})
					setTimeout(()=>{
						uni.switchTab({
							url: '../../../pages/diary/index'
						})
					},500)
				})
			}else{
				if(!self.title){
					uni.showToast({
						title:'标题不能为空',
						duration:500,
						icon:'none'
					})
					return false
				}
				if(self.fileList.length == 0){
					uni.showToast({
						title:'请先上传图片',
						duration:500,
						icon:'none'
					})
					return false
				}
				let data = {
					cover: self.fileList[0],
					locationLatitude: self.latitude,
					locationLongitude: self.longitude,
					locationName: self.address,
					content: self.content,
					mediaUrl: self.fileList.toString(),
					petId: self.pid,
					showFlag: self.active?1:0,
					status: e,
					title: self.title,
					type: 1,
					videoId: self.videoId
				}
				self.$request(self.commonApi.diaryAdd,'POST',data,'application/json').then(res=>{
					uni.showToast({
						title:'操作成功',
						duration:500,
						icon:'none'
					})
					setTimeout(()=>{
						uni.switchTab({
							url: '../../../pages/diary/index'
						})
					},500)
				})
				
			}
		},
		delVideo(i){
			this.srcList.splice(i,1)
		},
		test() {
			if(this.srcList.length < 1){
				let self = this;
				uni.chooseVideo({
					compressed: false,
					success: function (res) {
						let file = {url: res.tempFilePath, coverUrl: res.thumbTempFilePath};
						let userData = '{"Vod":{}}';
						uploader.addFile(file, null, null, null, userData)
						self.$request(self.commonApi.stsToken,'GET').then(result=>{
							uploader.setSTSToken(file, result.data.data.accessKeyId, result.data.data.accessKeySecret, result.data.data.secretToken)
						})
					}
				})
			}
		},
		getData(){  //修改草稿有id调用
			let self = this
			self.$request(self.commonApi.diaryId+self.options.id,'GET').then(res=>{
				let data = res.data.data
				if(self.options.type == 1){
					self.petValue = data.petName
					self.title = data.title
					self.content = data.content
					self.active = data.showFlag
					let images = data.mediaUrl.split(',')
					images.forEach(item=>{
						self.fileList.push(item)
					})
					console.log(self.fileList)
				}
				if(self.options.type == 2){
					self.petValue = data.petName
					self.title = data.title
					self.videoId = data.videoId
					self.srcList.push(data.mediaUrl)
					self.active = data.showFlag
				}
			})
		},
	},
	mounted() {
		this.getPet()
		let self = this;
		uni.getLocation({
		    type: 'wgs84',
		    success: function (res) {
				self.longitude = res.longitude
				self.latitude = res.latitude
				let location = res.longitude+','+res.latitude
				self.$request('https://restapi.amap.com/v3/geocode/regeo?key=50df9f27e9d94fbeccfab13ff5d004d6&location='+location,'GET').then(res=>{
				}).catch(err=>{
					self.address = err.data.regeocode.formatted_address
				})
		    }
		});
	},
	onLoad(option) {
		this.options = option
		if(option.id){
			this.getData()
			return false
		}
		this.delVideo(0)
		if(option.dataList){
			let dataList = JSON.parse(option.dataList)
			this.title = dataList.title
			this.content = dataList.content
			this.petValue = dataList.petValue
			this.pid = dataList.pid
			let data = dataList.imgFlieList.split(',')
			if(data.length != 0){
				data.forEach(item=>{
					if(item.split('.')[1] == 'png' || item.split('.')[1] == 'jpg' || item.split('.')[1] == 'jpeg'){
						this.fileList2.push(item)
						this.fileList2 = Array.from(new Set(this.fileList2))
					}
				})
				if(this.fileList2.length > 0){
					this.setUploadImg(0)
				}
				if(data[0].split('.')[1] == 'mp4'){
					let file = {url: data[0], coverUrl: data[0]};
					let userData = '{"Vod":{}}';
					uploader.addFile(file, null, null, null, userData)
					this.$request(this.commonApi.stsToken,'GET').then(result=>{
						uploader.setSTSToken(file, result.data.data.accessKeyId, result.data.data.accessKeySecret, result.data.data.secretToken)
					})
				}
			}
		}
		
		
	}
};
</script>

<style lang="scss" scoped>
	.file-buttom{
		width: 100%;
		height: 100rpx;
		background: white;
		display: flex;
		align-items: center;
		font-size: 28rpx;
		font-weight: 600;
		justify-content: center;
		border-bottom: 1px solid #f2f2f2;
		span{
			color: #FA3534;
		}
	}
	.fileView-nik{
		width: 700rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		padding-bottom: 20px;
	}
	.fileView{
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.upload-del{
		position: absolute;
		top: 10rpx;
		right: 10rpx;
		width: 45rpx;
		height: 45rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #FA3534;
		z-index: 10;
	}
	.uploads-add{
		width: 200rpx;
		height: 200rpx;
		background: #f4f5f6;
		border-radius: 15rpx;
		margin-right: 25rpx;
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin-bottom: 20rpx;
	}
	.uploads{
		width: 200rpx;
		height: 200rpx;
		background: #f4f5f6;
		border-radius: 15rpx;
		margin-right: 25rpx;
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin-bottom: 20rpx;
		image{
			position: absolute;
			top: 0;
			left: 0;
			width: 200rpx;
			height: 200rpx;
			// background: #f4f5f6;
			border-radius: 15rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
		}
	}
	.content-upload {
		width: 700rpx;
		padding: 25rpx 0;
		font-size: 28rpx;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
	}



	.table-name {
		width: 700rpx;
		height: 120rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-direction: row;
		font-size: 32rpx;
		color: #333333;
		border-bottom: 1px solid #f2f2f2;
		span:nth-of-type(2){
			height: 120rpx;
			display: flex;
			align-items: center;
			flex-direction: row-reverse;
		}
	}
	.styleCss{
		width: 520rpx;
	}
	.save{
		width: 160rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		font-size: 28rpx;
		color: #999999;
		image{
			width: 40rpx;
			height: 40rpx;
			margin-bottom: 5rpx;
		}
	}
	.commit{
		width: 100%;
		height: 120rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: white;
		z-index: 100;
		position: fixed;
		bottom: 0;
		left: 0;
		.commit-nik{
			width: 700rpx;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			flex-direction: row;
		}
	}
	.table-location{
		width: 700rpx;
		display: flex;
		align-items: center;
		flex-direction: row;
		padding: 25rpx 0;
		.location-item{
			padding: 10rpx 20rpx;
			display: flex;
			align-items: center;
			flex-direction: row;
			border-radius: 50rpx;
			background: #EEEEEE;
			font-size: 28rpx;
			color: #999999;
			view{
				padding-left: 15rpx;
			}
		}
		.location-item2{
			padding: 10rpx 20rpx;
			display: flex;
			align-items: center;
			flex-direction: row;
			border-radius: 50rpx;
			background: #FF9A00;
			font-size: 28rpx;
			color: white;
			view{
				padding-left: 15rpx;
			}
		}
	}
	.addItems-icon{
		width: 50rpx;
		height: 50rpx;
		border-radius: 50rpx;
		background: red;
		display: flex;
		align-items: center;
		justify-content: center;
		position: absolute;
		top: 0;
		right: 0;
		z-index: 10;
	}
	.addPload-waik{
		width: 100%;
		min-height: 210rpx;
		display: flex;
		align-items: center;
		flex-direction: row;
		flex-wrap: wrap;
		margin-top: -20rpx;
		padding-bottom: 10rpx;
		.addItem{
			width: 210rpx;
			height: 210rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 20rpx;
			border: 2px dashed #f2f2f2;
			margin-right: 20rpx;
			margin-top: 20rpx;
			
		}
	}
	.addPload{
		width: 210rpx;
		min-height: 210rpx;
		display: flex;
		align-items: center;
		flex-direction: row;
		flex-wrap: wrap;
		margin-right: 20rpx;
		margin-top: 20rpx;
		.addItems{
			width: 210rpx;
			height: 210rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;
			// padding: 2px 0;
			video{
				width: 210rpx;
				height: 210rpx;
				border-radius: 20rpx;
			}
		}
		
	}
	.table-cloum{
		width: 700rpx;
		display: flex;
		flex-direction: column;
		padding-bottom: 20rpx;
		span{
			width: 100%;
			padding: 35rpx 0 25rpx 0;
			display: flex;
			align-items: center;
			font-size: 28rpx;
			font-weight: bold;
		}
		textarea{
			width: 660rpx;
			height: 160rpx;
			background: #f6f6f6;
			padding: 20rpx;
			border-radius: 20rpx;
		}
	}
	.table-item{
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: row;
		background: white;
		border-bottom: 1px solid #f2f2f2;
	}
	.taxt{
		width: 700rpx;
		height: 200rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 20rpx 0;
		textarea{
			width: 700rpx;
			line-height: 45rpx;
			height: 200rpx;
		}
	}
	.title{
		width: 700rpx;
		height: 100rpx;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		flex-direction: row;
		font-weight: bold;
		border-bottom: 1px solid #f2f2f2;
	}
.content {
	width: 100%;
	display: flex;
	align-items: center;
	flex-direction: column;
}
</style>
